import 'package:flutter/material.dart';
import 'package:note/common/common.dart';
import 'package:get/get.dart';
import 'package:note/pages/edit_note_page/logic.dart';

import '../state.dart';

class EditToolBar extends StatelessWidget {
  final EditNotePageState state;

  const EditToolBar({super.key, required this.state});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
      child: SafeArea(
        top: false,
        bottom: true,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            addSignBase('`'),
            addSignBase('.'),
            addSignBase('-'),
            addSignBase('_'),
            addSignBase('*'),
            addSignBase('#'),
            addSignBase('()'),
            addSignBase('[]'),
            // addPhoto(),
          ],
        ),
      ),
    );
  }

  Widget addPhoto() {
    return Expanded(
      child: InkWell(
        onTap: () {
          if (Get.isRegistered<EditNotePageLogic>()) {
            Get.find<EditNotePageLogic>().onAddPhoto();
          } else {}
        },
        child: const Padding(
          padding: EdgeInsets.all(8.0),
          child: Icon(
            Icons.add_photo_alternate_outlined,
            size: 25,
            color: Styles.mainThemeColor,
          ),
        ),
      ),
    );
  }

  Widget addSignBase(String text) {
    return Expanded(
      child: InkWell(
        onTap: () {
          TextEditingController controller;
          if (state.titleFocusNode.hasFocus) {
            controller = state.titleController;
          } else if (state.contentFocusNode.hasFocus) {
            controller = state.contentController;
          } else {
            //未聚焦任何地方
            state.contentFocusNode.requestFocus();
            controller = state.contentController;
            return;
          }
          // 获取当前光标的位置
          int cursorPosition = controller.selection.baseOffset;
          // 使用字符串切片将原始字符串分成两段，并在中间插入字符
          String firstPart = controller.text.substring(0, cursorPosition);
          String secondPart = controller.text.substring(cursorPosition);
          // 更新文本和光标位置
          controller.value = controller.value.copyWith(
            text: firstPart + text + secondPart,
            selection: TextSelection.collapsed(
                offset: cursorPosition + (text.length == 2 ? 1 : text.length)),
          );
        },
        child: Container(
          padding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
          alignment: Alignment.center,
          child: Text(
            text,
            style: Styles.textThemeBold(20),
          ),
        ),
      ),
    );
  }
}
